package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.SQLListDoing;
import com.rockcent.mall.lib.domain.ProductStatistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by DK on 16/10/25.
 */
@Repository
public class MerchantProductStatisticsRepositoryImpl implements MerchantProductStatisticsRepositoryCustom{
    private static final Logger log = LoggerFactory.getLogger(MerchantProductStatisticsRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public List<ProductStatistics> getTop10(Integer size,Long mallId){
        SQLListDoing<ProductStatistics> doing = (sql, fields, params, typeReferenceMap)->{
            sql.append("SELECT ps.* FROM product_statistics ps where ps.mall_id = :mallId ORDER BY ps.view_count  DESC LIMIT 0,:size");
            params.put("mallId",mallId);
            params.put("size",size);
        };
        return doing.go(ProductStatistics.class, jdbcTemplate, log, objectMapper);
    }
    @Override
    public List<ProductStatistics> getTopSale20(Long merchantId,Long mallId){
        SQLListDoing<ProductStatistics> doing = (sql, fields, params, typeReferenceMap)->{
            sql.append("SELECT ps.* FROM product_statistics ps ,product p  where ps.product_id = p.id and p.market_id is null  and ps.merchant_id =:merchantId and ps.mall_id = :mallId ORDER BY ps.sale_count DESC , ps.last_updated desc LIMIT 0,20");
            params.put("merchantId",merchantId);
            params.put("mallId",mallId);
        };
        return doing.go(ProductStatistics.class, jdbcTemplate, log, objectMapper);
    }
    public List<ProductStatistics> findByProductIdInCustom(List<Long> productIds,String orderBy){
        SQLListDoing<ProductStatistics> doing = (sql, fields, params, typeReferenceMap)->{
            sql.append("SELECT ps.* FROM product_statistics ps where ps.product_id in(:productId) ");
            if ("All".equals(orderBy)){
                sql.append(" order by ps.sale_count desc,ps.view_count desc,click_count desc,order_count desc ");
            }else if ("saleCount".equals(orderBy)){
                sql.append(" order by ps.sale_count desc ");
            }
            params.put("productId",productIds);
        };
        return doing.go(ProductStatistics.class, jdbcTemplate, log, objectMapper);
    }

}
